import React, { useEffect, useState } from 'react';
import { Card, Table, Button, Modal, Image } from 'antd';
import { Form, Input, InputNumber, Radio, Upload, Tag, message, Cascader, Select } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { getGoodsList, solveGoods, forbidGoods, addGoods, editGoods } from '../../services/goods';
import { getCategory } from '../../services/category';

type Goods = {
  goodsId: number;
  goodsName: string;
  goodsIntro: string;
  goodsCategoryId: number;
  goodsCoverImg: string;
  originalPrice: number;
  sellingPrice: number;
  stockNum: number;
  tag: string;
  goodsSellStatus: number;
  createUser: number;
  createTime: string;
  updateUser: number;
  updateTime: string;
  goodsDetailContent: string;
};

const prefix = (url: string) => {
  if (url && url.startsWith('http')) {
    return url;
  } else {
    return `http://localhost:8080${url}`;
  }
};

const GoodsAdmin = () => {
  const [goods, setGoods] = useState<Goods[]>([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [categoryData, setCategoryData] = useState([]);
  const [goodForm, setGoodForm] = useState<Partial<Goods>>({});
  const [categoryId, setCategoryId] = useState<number>();
  const [modalTitle, setModalTitle] = useState('新增商品');
  const [modalLoading, setModalLoading] = useState(false);
  const [goodsName, setGoodsName] = useState('');
  const [goodsSellStatus, setGoodsSellStatus] = useState<0 | 1>();

  const fetchData = () => {
    setLoading(true);
    getGoodsList({
      pageNumber: pagination.current as number,
      pageSize: pagination.pageSize as number,
      goodsName,
      goodsSellStatus,
    }).then((res) => {
      setGoods(res.data?.list || []);
      setPagination({
        ...pagination,
        total: res.data?.totalCount,
      });
      setLoading(false);
    });
  };

  const handleOk = async () => {
    setModalLoading(true);

    const http = goodForm.goodsId ? editGoods : addGoods;
    goodForm.goodsCategoryId = categoryId;
    await http(goodForm);
    message.success(goodForm.goodsId ? '修改成功' : '添加成功');
    setModalLoading(false);
    setVisible(false);
    fetchData();
  };

  const handleCancel = () => {
    setVisible(false);
  };

  const handleForbidGoods = (userId: number) => {
    forbidGoods([userId]).then(() => {
      message.success('商品下架成功');
      fetchData();
    });
  };

  const handleSolveGoods = (userId: number) => {
    solveGoods([userId]).then(() => {
      message.success('商品上架成功');
      fetchData();
    });
  };

  const handleLoadData = (treeNode: any) => {
    const targetOption = treeNode[treeNode.length - 1];
    const { level, value } = targetOption;

    if (level < 3) {
      getCategory({
        pageNumber: 1,
        pageSize: 1000,
        categoryLevel: level + 1,
        parentId: value || 0,
      }).then((res) => {
        const list = res.data.list;
        if (list.length === 0) {
          targetOption.isLeaf = true;
          setCategoryData([...categoryData]);
          return;
        }
        const nodes = list.map((item) => ({
          value: item.categoryId,
          label: item.categoryName,
          level: level + 1,
          isLeaf: level === 2,
        }));

        targetOption.children = nodes;
        setCategoryData([...categoryData]);
      });
    }
  };

  const handleChangeCate = (value: any[]) => {
    if (value.length === 2) {
      setCategoryId(value[1]);
    } else if (value.length === 3) {
      setCategoryId(value[2]);
    } else setCategoryId(0);
  };

  const handleChange = (info: any) => {
    if (info.file.status === 'done') {
      setGoodForm({
        ...goodForm,
        goodsCoverImg: info.file.response.data,
      });
    }
  };

  useEffect(() => {
    fetchData();
  }, [JSON.stringify(pagination)]);

  useEffect(() => {
    getCategory({
      pageNumber: 1,
      pageSize: 10,
      categoryLevel: 1,
      parentId: 0,
    }).then((res) => {
      const nodes = res.data?.list.map((item) => ({
        value: item.categoryId,
        label: item.categoryName,
        level: 1,
        isLeaf: false,
      }));
      setCategoryData(nodes as any);
    });
  }, []);

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );

  const columns: ColumnsType<Goods> = [
    {
      title: '商品编号',
      dataIndex: 'goodsId',
    },
    {
      title: '商品名',
      dataIndex: 'goodsName',
      width: 400,
    },
    {
      title: '商品简介',
      dataIndex: 'goodsIntro',
      width: 400,
    },
    {
      title: '商品图片',
      render: (_, item: Goods) => (
        <div>
          <Image width={100} src={prefix(item.goodsCoverImg)} />
        </div>
      ),
    },
    {
      title: '商品库存',
      dataIndex: 'stockNum',
    },
    {
      title: '商品售卖价',
      dataIndex: 'sellingPrice',
    },
    {
      title: '销售状态',
      render: (_, item: Goods) => {
        if (item.goodsSellStatus === 0) {
          return <Tag color="success">销售中</Tag>;
        } else {
          return <Tag color="error">已下架</Tag>;
        }
      },
    },
    {
      title: '操作',
      render: (_, item: Goods) => {
        return (
          <span>
            <Button
              color="processing"
              style={{ marginRight: '10px' }}
              onClick={() => {
                setModalTitle('修改商品');
                setCategoryId(item.goodsCategoryId);
                setGoodForm(item);
                setVisible(true);
              }}
            >
              修改
            </Button>
            {item.goodsSellStatus === 0 && (
              <Button danger onClick={() => handleForbidGoods(item.goodsId)}>
                下架
              </Button>
            )}
            {item.goodsSellStatus === 1 && (
              <Button type="primary" onClick={() => handleSolveGoods(item.goodsId)}>
                上架
              </Button>
            )}
          </span>
        );
      },
    },
  ];

  return (
    <>
      <Card>
        <div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setModalTitle('新增商品');
              setGoodForm({});
              setVisible(true);
            }}
            style={{ marginRight: '10px', marginBottom: '10px' }}
          >
            新增商品
          </Button>
          <Input
            placeholder="请输入商品名称"
            onChange={(e) => setGoodsName(e.target.value)}
            style={{ width: 200, marginRight: '10px' }}
          />
          <span style={{ marginRight: '5px' }}>商品状态</span>
          <Select
            style={{ width: 120 }}
            allowClear
            options={[
              { value: 0, label: '上架' },
              { value: 1, label: '下架' },
            ]}
            onChange={(value) => {
              setGoodsSellStatus(value);
            }}
          />
          <Button
            onClick={() => {
              fetchData();
            }}
            style={{ marginLeft: '10px', marginBottom: '10px' }}
          >
            搜索
          </Button>
        </div>
        <Table
          columns={columns}
          pagination={{
            ...pagination,
            onChange: (page, pageSize) => {
              setPagination({
                ...pagination,
                current: page,
                pageSize,
              });
            },
          }}
          dataSource={goods}
          loading={loading}
        />
      </Card>
      <Modal
        title={modalTitle}
        open={visible}
        okText="确认"
        destroyOnClose
        onCancel={handleCancel}
        footer={[
          <Button key="back" onClick={handleCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" loading={modalLoading} onClick={handleOk}>
            确认
          </Button>,
        ]}
      >
        <Form labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
          <Form.Item label="商品分类">
            <Cascader
              style={{ width: 300 }}
              options={categoryData}
              loadData={handleLoadData}
              onChange={handleChangeCate}
            />
          </Form.Item>
          <Form.Item label="商品名称">
            <Input
              value={goodForm.goodsName}
              onChange={(e) => {
                setGoodForm({
                  ...goodForm,
                  goodsName: e.target.value,
                });
              }}
            ></Input>
          </Form.Item>
          <Form.Item label="商品简介">
            <Input
              value={goodForm.goodsIntro}
              onChange={(e) => {
                setGoodForm({
                  ...goodForm,
                  goodsIntro: e.target.value,
                });
              }}
            ></Input>
          </Form.Item>
          <Form.Item label="商品价格">
            <InputNumber
              value={goodForm.originalPrice}
              onChange={(value) => {
                setGoodForm({
                  ...goodForm,
                  originalPrice: value as number,
                });
              }}
            ></InputNumber>
          </Form.Item>
          <Form.Item label="商品售卖价">
            <InputNumber
              value={goodForm.sellingPrice}
              onChange={(value) => {
                setGoodForm({
                  ...goodForm,
                  sellingPrice: value as number,
                });
              }}
            ></InputNumber>
          </Form.Item>
          <Form.Item label="商品库存">
            <InputNumber
              value={goodForm.stockNum}
              onChange={(value) => {
                setGoodForm({
                  ...goodForm,
                  stockNum: value as number,
                });
              }}
            ></InputNumber>
          </Form.Item>
          <Form.Item label="上架状态">
            <Radio.Group
              value={goodForm.goodsSellStatus}
              onChange={(e) => {
                setGoodForm({
                  ...goodForm,
                  goodsSellStatus: e.target.value,
                });
              }}
            >
              <Radio value={0}>上架</Radio>
              <Radio value={1}>下架</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="商品图片">
            <Upload
              name="file"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://localhost:8080/manage-api/v1/upload/file"
              headers={{
                token: localStorage.getItem('token'),
              }}
              onChange={handleChange}
              accept=".jpg,.png"
            >
              {goodForm.goodsCoverImg ? (
                <img src={prefix(goodForm.goodsCoverImg)} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <Form.Item label="商品详情">
            <Input
              value={goodForm.goodsDetailContent}
              onChange={(e) => {
                setGoodForm({
                  ...goodForm,
                  goodsDetailContent: e.target.value,
                });
              }}
            ></Input>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default GoodsAdmin;
